import { TableInfo } from "@/entities/tableInfo.entity";
import createFile from "./createFile";

/**
 * 创建实体类代码
 * @param data 
 * @returns 
 */
const createEntityCode = async (data: TableInfo) => {
    const { name, fieldInfoList = [], indexInfoList = [] } = data;
    //表名下划线转大驼峰
    const bigName = name.replace(/(?:^|_)(\w)/g, (_, c) => c.toUpperCase());
    const smallName = name.replace(/_(.)/g, (a: string, b: string) => `${b.toLocaleUpperCase()}`);

    let str = `
import { Entity,  Column,  Index, PrimaryGeneratedColumn,CreateDateColumn,UpdateDateColumn } from 'typeorm';
            ${indexInfoList.map(item => {
        return `
@Index('${item.indexType == "UNIQUE" ? "uk" : "idx"}_${item.smallHumpCode!.split(',').join("_")}',['${item.smallHumpCode!.replace(/,/g, `','`)}'],{ unique: ${item.indexType == "UNIQUE" ? "true" : "false"} })           
`
    }).join("")
        }
@Entity("${name}")
export class ${bigName} {
            ${fieldInfoList.map(item => {
            // 将下划线转小驼峰
            const filedName = item.smallHumpCode;
            //创建时间和更新时间单独处理
            if (filedName == "createdAt") {
                return `
    @CreateDateColumn({
        name: 'created_at',
        type: 'datetime',
        default: () => 'CURRENT_TIMESTAMP',
        nullable: false,
        comment: '创建时间',
        precision:0
    })
    createdAt!: Date;              
                `

            } else if (filedName == "updatedAt") {
                return `
    @UpdateDateColumn({
        name: 'updated_at',
        type: 'datetime',
        default: () => 'CURRENT_TIMESTAMP',
        onUpdate: 'CURRENT_TIMESTAMP',
        nullable: false,
        comment: '更新时间',
        precision:0
    })
    updatedAt!: Date;
                `
            }
            //处理其他字段
            const isNumber = ["tinyint", 'int', 'integer', 'smallint', 'mediumint', 'bigint', 'decimal', 'numeric'].indexOf(item.dataType as string) != -1;
            // 在typeScript里面是否可为空，
            const isNodeCanEmpty = item.isNull || item.defaultValue;

            if (item.isKey) {
                return `
    @PrimaryGeneratedColumn({ name: '${filedName}', type: '${item.dataType}', comment: '${item.name}' })
    ${filedName}${isNodeCanEmpty ? '?' : '!'}: ${isNumber ? 'number' : 'string'};
                `
            } else {
                return `
    @Column({
        name: '${item.code}',
        type: '${item.dataType}',
        ${item.dataTypeLength ? `length: ${item.dataTypeLength}, ` : ""}
        nullable: ${item.isNull ? "true" : "false"},
        comment: '${item.name}',
        ${item.defaultValue ? `default: ${item.defaultValue},` : ''}                    
    })
    ${filedName}${isNodeCanEmpty ? '?' : '!'}: ${isNumber ? 'number' : 'string'};
                `
            }

        }).join("")
        }
}
`;



    await createFile(str, `entities/${smallName}.entity.ts`)
    return str;


}
export default createEntityCode